package Test_1101;

/**
 * Created with Intellij IDEA
 * Description:
 * User: 星辰
 */
public class MySingleList implements IList{
    static class ListNode{
        public int val;
        public ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode head;
    //头插
    @Override
    public void addFirst(int data) {
        ListNode node=new ListNode(data);
        node.next=head;
        head=node;
    }

    @Override
    //尾插：
    // 是否为空
    public void addLast(int data) {
        ListNode node=new ListNode(data);
        while(head!=null){
            head=node;
            return;
        }
        ListNode cur=head;
        //到最后一个cur.next
        while(cur.next!=null){
            cur=cur.next;
        }
        cur.next=node;
    }
//插入位置是否合法
    @Override
    public void addindex(int index, int data) {
        ListNode node=new ListNode(data);
        int len=size();
        if(index<0 || index>=len){
            System.out.println("index不合法");
            return;
        }
         //头插入
        if(index==0){
            addFirst(data);
        }
        //尾
        if(index==len){
            addLast(data);
        }
        //插入中间位置
        ListNode cur=head;
        while(index-1!=0){
            cur=cur.next;
            index--;
        }
        node.next=cur.next;
        cur.next=node;
    }

    @Override
    public boolean contains(int key) {
        ListNode cur=head;
        while(cur!=null){
            if(cur.val==key){
                return true;
            }
            cur=cur.next;
        }
        return false;
    }

    @Override
    public void remove(int key) {
        ListNode cur=head;
        ListNode del=new ListNode(key);
        while(cur!=null){
            if(cur.next.val==key){
                del.next=cur.next;
                cur.next=del;
            }

        }
    }

    @Override
    public void removeAllKey(int key) {

    }

    @Override
    public void clear() {

    }

    @Override
    public int size() {
        int len=0;
        ListNode cur=head;
        while(cur!=null){
            cur=cur.next;
            len++;
        }
        return len;
    }

    @Override
    public void display() {
         ListNode cur=head;
         while(cur!=null){
             System.out.print(cur.val+" ");
             cur=cur.next;
         }
    }
}
